const { promisify } = require("util");
const path = require("path");
const program = require("commander");
const chalk = require("chalk");
const { spawn } = require('child_process');

const download = promisify(require("download-git-repo"));
const open = require("open");

const { vueRepo } = require("../config/repo-config");
const { commandSpawn, syncSpawn } = require("../utils/terminal");
const { compile, writeToFile, createDirSync } = require("../utils/utils");

// callback -> promisify(函数) -> Promise -> async await
const createProjectAction = async (project) => {
  console.log("why helps you create your project~");

  // 1.clone项目
  await download(vueRepo, project, { clone: true });
  console.log(chalk.blue("项目开始下载~"));
  // 2.执行npm install
  const command = process.platform === "win32" ? "npm.cmd" : "npm";
  console.log(chalk.green("项目依赖开始下载~"));
  await commandSpawn(command, ["install"], { cwd: `./${project}` });
  console.log(chalk.cyan("项目依赖下载完成~"));
  // 3.运行npm run serve
  commandSpawn(command, ["run", "serve"], { cwd: `./${project}` });

  // 4.打开浏览器
  open("http://localhost:8080/");
};

// 添加组件的action
const addComponentAction = async (name, dest) => {
  // 1.编译ejs模板 result
  const componentsTemplate = await compile("vue-component.ejs", {
    name,
    lowerName: name.toLowerCase(),
	type: "cpn"
  });

  // 2.写入文件的操作
  const targetPath = path.resolve(dest, `./${name}.vue`);
  // 3.直接创建文件夹函数 这里需要判断真实的dest是否存在
  if (program.dest) createDirSync(path.resolve(dest));

  // 4.文件写入
  await writeToFile(targetPath, componentsTemplate);
  console.log(chalk.blueBright("vue组件创建完成！"));
};

const addPageAction = async (name, dest) => {
  // 先拿到文件模板
  const data = { name, lowerName: name.toLowerCase() };
  const pageTemplate = await compile("vue-component.ejs", data);
  const componentsTemplate = await compile("vue-component.ejs", data);
  const base_dir = path.resolve(dest, `./${name}`, "index.vue");
  // 再来一个子文件下下面的文件夹
  const base_child_dir = path.resolve(
    dest,
    `./${name}`,
    "./comps",
    `${name}_comp.vue`
  );
  // 需要判断下 dest是否存在
  createDirSync(path.resolve(dest, `./${name}`, "./comps"));
  await writeToFile(base_dir, pageTemplate);
  await writeToFile(base_child_dir, componentsTemplate);
  console.log(chalk.blueBright("页面创建完成！"));
};

const ctrlAction = (url) => open(url);

const pushAction = async (commitInfo, pathName) => {
   await commandSpawn("git", ["add", '.'], { cwd: pathName });	
   await commandSpawn("git", ["commit", "-m", commitInfo], { cwd: pathName });
   await commandSpawn("git", ["push", "-u", "origin", "master"], { cwd: pathName });
   console.log(chalk.blueBright("提交完成~"));
};

module.exports = {
  createProjectAction,
  addComponentAction,
  addPageAction,
  ctrlAction,
  pushAction,
};
